import { message } from 'antd';
import { intercept, FetchBusy, IFetchInterceptor } from '.';

export class FetchAdapter implements IFetchInterceptor {
  request(request: Request) {
    const headers = {
      ...request.headers,
      'Content-Type': 'application/json',
      token: '',
    };

    const newRequest = {
      ...request,
      headers,
    };

    return newRequest;
  }

  requestError(error: any) {
    return Promise.reject(error);
  }

  async response(response: Response) {
    if (response.status === 204) {
      message.destroy();
      return response;
    }

    if (response.status >= 400) {
      message.destroy();
      message.error(response.statusText || '网络错误，请重新操作');
      return Promise.reject(response);
    }

    const json = await response.clone().json();

    if (!!json.errorCode) {
      // 鉴权失败需要跳转到登录页面的提示
      const popMessage = json.errorCode !== 403 && json.code !== 'NO_SESSION';
      popMessage && message.error(json.errorMessage);
      if (json.errorCode === 403 && json.code === 'NO_SESSION') {
        // 跳转到登录页面
      }
      return Promise.reject(json);
    }
    return response;
  }

  responseError(error: any) {
    return Promise.reject(error);
  }
}

export function Fetch(fetch = intercept(window.fetch)) {
  let hideLoading: any = null;
  fetch.use(
    new FetchBusy((loading: boolean) => {
      if (loading) {
        hideLoading = message.loading('加载中', 0);
      } else {
        hideLoading && hideLoading();
      }
    })
  );
  fetch.use(new FetchAdapter());

  return fetch;
}

export default function setCollection() {
  const _fetch_ = Fetch();
  (window as any)._fetch_ = _fetch_;
}
